import 'dart:async';
import 'dart:io';

import 'package:chathouse/constant/my_color.dart';
import 'package:chathouse/constant/res.dart';
import 'package:chathouse/pages/expert/home_page.dart';
import 'package:chathouse/pages/expert/mine_page.dart';
import 'package:chathouse/pages/expert/projects_page.dart';
import 'package:chathouse/public/event_bus.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../constant/app_constant.dart';
import '../../model/app_version.dart';
import '../../model/member_info.dart';
import 'package:chathouse/model/shield.dart';
import '../../net/Apis.dart';
import '../../public/Global.dart';
import '../../push/chat_house_push.dart';
import '../../util/SpUtil.dart';
import '../../util/font_utils.dart';
import '../../util/image_utils.dart';
import '../../util/log.dart';
import '../../web_socket/web_socket_channel.dart';
import '../../widgets/app_update_widget.dart';
import '../../widgets/custom_floating_button.dart';
import '../../widgets/no_scaling_animation.dart';
import '../route_manager/root_route_manager.dart';
import 'notice_page.dart';
import 'service_demand_page.dart';

///入口
class ExpertRootPage extends StatefulWidget {
  const ExpertRootPage({Key? key}) : super(key: key);

  @override
  State<ExpertRootPage> createState() => _ExpertRootPageState();
}

class _ExpertRootPageState extends State<ExpertRootPage> {
  var noReadSericeNum = -1;
  var noticeNoReadNumber = -1;
  // Shield? shield;
  // List<Rows>? rows = [];

  Timer? timer;
  StreamSubscription? refreshSubscription;
  RootRouteController rootRouteController = RootRouteController(0, [
    const Homepage(),
    const ServiceDemandPage(),
    const MinePage(),
    NoticePage(),
    const ProjectsPage()
  ]);

  @override
  void initState() {
    super.initState();
    loadMessageNum();
    AppConstant.rootController = rootRouteController;
    refreshSubscription = eventBus.on<UpdateRootIndexEvent>().listen((event) {
      if (!mounted) return;
      jumpPage(event.idx ?? 2);
    });
    Apis.getMembersInfo().then((value) {
      var jsonData = value?.data;
      var _memberInfo = MemberInfo.fromJson(jsonData);
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo);
      MyWebSocketChannel.instance.initSocket();
      setState(() {});
    }).catchError((error) {
      LogUtil.d("getMembersInfo error");
    });

    timer = Timer.periodic(const Duration(seconds: 30), (Timer timer) {
      loadMessageNum();
    });

    Apis.getAppVersion().then((value) async {
      LogUtil.d("getAppVersion后台返回数据：$value");
      var data = value?.data ?? {};
      var appModel = AppVersion.fromJson(data);
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      String version = packageInfo.version;
      version = version.replaceAll(".", "");
      bool isForcedUpdate = appModel.data?.isForcedUpdate ?? false;
      String newAppVersion = appModel.data?.appVersion ?? "0";
      newAppVersion = newAppVersion.replaceAll(".", "") ?? "0";
      int newVersion = int.parse(newAppVersion);
      int currentVersion = int.parse(version);
      LogUtil.d("newAppVersion：$newVersion");
      LogUtil.d("currentVersion：$currentVersion");
      if (newVersion > currentVersion) {
        AppUpdateWidget.showUpdateDialog(
            appModel.data?.updateMsg ?? "", appModel.data?.appVersion ?? "",
            isForcedUpdate: isForcedUpdate);
      }
    }).catchError((error) {
      LogUtil.d("getAppVersion Error ${error}");
    });
  }

  loadMessageNum() {
    final params = {"kind": "1"};
    Apis.readNum(params).then((value) {
      print('readNum value:');
      print(value.toString());
      if (value == null || value.data == null) {
        return;
      }
      noReadSericeNum = value.data["data"]["projectReadNum"];
      noticeNoReadNumber = value.data["data"]["seslistReadNum"];
      SpUtil.putInt(Keys.seslistReadNum, value.data["data"]["seslistReadNum"]);
      setState(() {});
      if (Platform.isAndroid) {
        _showBadge(noReadSericeNum + noticeNoReadNumber);
      } else {
        ChatHousePush.instance.jpush
            .setBadge(noReadSericeNum + noticeNoReadNumber);
      }
    }).onError((error, stackTrace) {});
  }

  // void loadService() {
  //   final params = {
  //     "pageNum": 1,
  //   };
  //   Apis.Shieldlist(params)
  //       .then((response) {
  //     shield = Shield.fromJson(response?.data);
  //     // rows?.addAll(shield?.rows ?? []),
  //     noticeNoReadNumber = shield?.rows?.where((element) => element.readFlag != 1).length??0;
  //     setState(() {});
  //   })
  //       .onError((error, stackTrace) {});
  // }

  Future<Null> _showBadge(int num) async {
    const badgeChannel = MethodChannel("chathouse.flutter");
    try {
      final result = await badgeChannel.invokeMethod('getBadge', {
        "badgeNum": num,
      });
    } on PlatformException catch (e) {
      if (kDebugMode) {
        LogUtil.d("_showBadge error: ${e.message}");
      }
    }
    // if(num == 0){
    //   FlutterAppBadger.removeBadge();
    // }else{
    //   FlutterAppBadger.updateBadgeCount(num);
    // }
  }

  @override
  void dispose() {
    refreshSubscription?.cancel();
    rootRouteController.dispose();
    MyWebSocketChannel.instance.dispose();
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        body: rootRouteController.getRootPageBody(),
        bottomNavigationBar: SafeArea(
          child: SizedBox(
            height: 75.w,
            child: Stack(
              children: <Widget>[
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    decoration: const BoxDecoration(
                      // color: Styles.mainColor,
                      image: DecorationImage(
                          fit: BoxFit.fitWidth,
                          image: AssetImage(Res.img_expert_bottom)),
                    ),
                    height: 75.w,
                    child: Flex(
                      direction: Axis.horizontal,
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: InkWell(
                              onTap: () {
                                eventBus.fire(UpdateMemberInfo());
                                jumpPage(0);
                              },
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  ImageUtils.image(Res.icon_awesome_home,
                                      width: 35.w, height: 30.w),
                                  const SizedBox(height: 4),
                                  Text(
                                    "首頁",
                                    style: getTextStyle(12.sp,
                                        color: MyColors.white),
                                  ),
                                ],
                              )),
                        ),
                        Expanded(
                          flex: 1,
                          child: InkWell(
                              onTap: () {
                                eventBus.fire(UpdateExpertSerivce());
                                jumpPage(1);
                              },
                              child: Stack(
                                children: [
                                  Center(
                                    child: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: <Widget>[
                                        ImageUtils.image(Res.icon_order,
                                            width: 30.w, height: 30.w),
                                        const SizedBox(height: 4),
                                        Text("服務需求",
                                            style: getTextStyle(12.sp,
                                                color: MyColors.white))
                                      ],
                                    ),
                                  ),
                                  Visibility(
                                    visible: noReadSericeNum > 0,
                                    child: Positioned(
                                        right: 8,
                                        top: 4,
                                        child: Container(
                                          alignment: Alignment.center,
                                          width: 26.w,
                                          height: 25.w,
                                          decoration: const BoxDecoration(
                                            color: Colors.red,
                                            shape: BoxShape.circle,
                                          ),
                                          child: Text(
                                            noReadSericeNum > 99
                                                ? "99+"
                                                : "$noReadSericeNum",
                                            textAlign: TextAlign.center,
                                            style: getTextStyle(11.sp,
                                                color: Colors.white,
                                                fontType: FontType.MID),
                                          ),
                                        )),
                                  ),
                                ],
                              )),
                        ),
                        Expanded(
                          flex: 1,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: const <Widget>[],
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: InkWell(
                            onTap: () {
                              jumpPage(3);
                            },
                            // child: Column(
                            //   mainAxisSize: MainAxisSize.min,
                            //   children: <Widget>[
                            //     ImageUtils.image(Res.message_push,
                            //         width: 30.w, height: 30.w),
                            //     const SizedBox(height: 4),
                            //     Text("通知",
                            //         style: getTextStyle(12.sp,
                            //             color: MyColors.white)),
                            //   ],
                            // )
                            child: Stack(
                              children: [
                                Center(
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      ImageUtils.image(Res.message_push,
                                          width: 30.w, height: 30.w),
                                      const SizedBox(height: 4),
                                      Text("通知",
                                          style: getTextStyle(12.sp,
                                              color: MyColors.white))
                                    ],
                                  ),
                                ),
                                Visibility(
                                  visible: noticeNoReadNumber > 0,
                                  child: Positioned(
                                      right: 8,
                                      top: 4,
                                      child: Container(
                                        alignment: Alignment.center,
                                        width: 26.w,
                                        height: 25.w,
                                        decoration: const BoxDecoration(
                                          color: Colors.red,
                                          shape: BoxShape.circle,
                                        ),
                                        child: Text(
                                          noticeNoReadNumber > 99
                                              ? "99+"
                                              : "$noticeNoReadNumber",
                                          textAlign: TextAlign.center,
                                          style: getTextStyle(11.sp,
                                              color: Colors.white,
                                              fontType: FontType.MID),
                                        ),
                                      )),
                                ),
                              ],
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: InkWell(
                              onTap: () {
                                jumpPage(4);
                              },
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  ImageUtils.image(Res.expertMine_orders,
                                      width: 38.w, height: 30.w),
                                  const SizedBox(height: 4),
                                  Text("我的項目",
                                      style: getTextStyle(12.sp,
                                          color: MyColors.white))
                                ],
                              )),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        floatingActionButtonAnimator: NoScalingAnimation(),
        floatingActionButtonLocation: FloatingButtonCustomLocation(
            FloatingActionButtonLocation.centerDocked,
            // offsetY: Platform.isIOS ? 0.w : 0,
            offsetX: 0),
        floatingActionButton: SafeArea(
          child: Align(
              alignment: Alignment.bottomCenter,
              child: Padding(
                padding: const EdgeInsets.only(bottom: 2.0),
                child: GestureDetector(
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: MyColors.red_0000016, width: 1),
                      color: Colors.white,
                      shape: BoxShape.circle,
                    ),
                    // padding: const EdgeInsets.all(3),
                    child: Container(
                      margin: const EdgeInsets.only(top: 4),
                      width: 78.w,
                      height: 78.w,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          const SizedBox(height: 6),
                          ImageUtils.image(Res.login_logo,
                              width: 47.w, height: 52.w),
                          Text("賬戶",
                              style: getTextStyle(12.sp,
                                  color: MyColors.green_69157608))
                        ],
                      ),
                    ),
                  ),
                  onTap: () {
                    eventBus.fire(UpdateMemberInfo());
                    jumpPage(2);
                  },
                ),
              )),
        ));
  }

  void jumpPage(int index) {
    rootRouteController.jumpToIndex(index);
    rootRouteController.cleanSubPageAndGoFirstPage(index);

    if (index == 1) //點擊訂單，訂單頁面 選擇全部TabItem
    {
      eventBus.fire(UpdateClientMessageEvent(0));
    }
    if (index == 4) //點擊讯息
    {
      eventBus.fire(UpdateClientMessageEvent(0));
    }
  }
}
